#!/usr/bin/env python
# -*- coding:utf-8 -*-
from datetime import datetime
import functools
import requests
import xlwt
import time

import math


def cal_time(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        start = time.time()
        func(self)
        end = time.time()
        print('{fun} time is {time}'.format(fun=func.__name__, time=end - start))

    return wrapper


class WechatSpider:

    def __init__(self, *args):
        self.result = []
        self.account_name = args
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0',
            'Cookie': your_cookie
        }
        self.excel_head = ['时间', '文章标题', '文章地址']
        self.url = 'https://mp.weixin.qq.com/cgi-bin/appmsg'
        self.begin = 0
        self.data = {
            # 登录用户的token
            "token": your_token,
            "lang": "zh_CN",
            "f": "json",
            "ajax": "1",
            "action": "list_ex",
            "begin": self.begin,
            "count": "5",
            "query": "",
            # 不同的公众号，fakeid不一样
            "fakeid": gzh_fakeid,
            "type": "9",
        }

    @staticmethod
    def excel_style():
        style = xlwt.XFStyle()
        alignment = xlwt.Alignment()
        alignment.horz = xlwt.Alignment.HORZ_CENTER  # 水平居中
        alignment.vert = xlwt.Alignment.VERT_CENTER  # 垂直居中
        style.alignment = alignment

        return style

    def write_to_excel(self, result, name):
        wbk = xlwt.Workbook()
        sheet = wbk.add_sheet('Sheet1')
        col_1 = sheet.col(0)
        col_2 = sheet.col(1)
        col_3 = sheet.col(2)
        col_4 = sheet.col(3)
        col_1.width = 256 * 18
        col_2.width = 256 * 45
        col_3.width = 256 * 30
        col_4.width = 256 * 150

        for index, head_name in enumerate(self.excel_head):
            sheet.write(0, index, head_name, WechatSpider.excel_style())

        for index, item in enumerate(result):
            sheet.write(index + 1, 0, item['date'], WechatSpider.excel_style())
            sheet.write(index + 1, 1, item['title'])
            sheet.write(index + 1, 2, item['url'])

        wbk.save('{name}_{date}.xls'.format(name=name, date=time.strftime('%Y-%m-%d')))

    def get_gzh_info(self, url):
        res = requests.get(url, headers=self.headers, params=self.data)
        if res.status_code == 200:
            json = res.json()
            count = json['app_msg_cnt']
            for item in json["app_msg_list"]:
                # 提取每页文章的标题及对应的url
                date = datetime.fromtimestamp(item["update_time"])
                d = {"title": item["title"], "url": item["link"], 'date': datetime.strftime(date, '%Y-%m-%d')}
                self.result.append(d)
            loop_count = math.ceil(count / 5)
            i = 0
            while loop_count > 1:
                time.sleep(5)
                i += 1
                loop_count -= 1
                self.begin = 5 * i
                self.get_gzh_info(url)

    @cal_time
    def run(self):
        assert self.account_name, 'WechatSpider初始化至少提供一个公众号名字'
        for name in self.account_name:
            self.get_gzh_info(self.url)
            self.write_to_excel(self.result, name)


if __name__ == '__main__':
    WechatSpider('不知了了').run()
